// Copyright 2009 Jan Hosang <jan.hosang@gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package builtin

import (
    "fmt"
    "os"
    "go/parser"
    "go/ast"
    "regexp"
    "container/list"
)

func GoImports(sources *list.List) *list.List {
    allImps := list.New()
    for src := range sources.Iter() {
        imports, err := getImports(src.(string))
        if err != nil {
            fmt.Printf("Warning: %v\n", err)
            continue
        }
        for imp := range imports.Iter() {
            allImps.PushBack(imp)
        }
    }
    return allImps
}

func getImports(filename string) (*list.List, os.Error) {
    prog, err := parser.ParseFile(filename, nil, nil, parser.ImportsOnly)
    if err != nil {
        return nil, err
    }

    visitor := newDependencyVisitor()
	ast.Walk(visitor, prog)
	return visitor.GetImports(), nil
}


type dependencyVisitor struct {
	imports *list.List
}

func newDependencyVisitor() *dependencyVisitor {
	return &dependencyVisitor{list.New()}
}

func (this *dependencyVisitor) GetImports() *list.List {
	return this.imports
}

func (this *dependencyVisitor) Visit(node interface{}) ast.Visitor {
	switch n := node.(type) {
	case *ast.ImportSpec:
        this.imports.PushBack(stripQuotes(string(n.Path.Value)));
	}
	return this
}

var unquote = regexp.MustCompile(`"(.+)"`)
func stripQuotes(quoted string) string {
	matches := unquote.MatchStrings(quoted)
	return matches[1]
}

